package permute_combine

import (
	C "gitee.com/ljfirst/algo-go-sdk/common/constant"
)

/**
 * @author ljfirst
 * @version V1.0
 * @date 2023/7/8 17:23
 * @author-Email ljfirst@mail.ustc.edu.cn
 * @blogURL https://blog.csdn.net/ljfirst
 * @description 时间的全排列
 * Given four digits, count how many valid times can be displayed on a digital clock (in 24-hour format) using those digits.
 * The earliest time is 00:00 and the latest time is 23:59.
 * */
type PermutationTime struct {
	timeArr []int
	count   int
	maxTime []int
}

func (m *PermutationTime) EligibleTimeNumMethod(timeArr []int) int {
	if len(timeArr) != 4 {
		return C.ErrorNum
	}
	m.timeArr = timeArr
	m.count = 0
	m.maxTime = make([]int, len(timeArr))
	for i := 0; i < len(timeArr); i++ {
		if timeArr[i] < 0 || timeArr[i] > 9 {
			return C.ErrorNum
		}
	}
	m.roll(0)
	return m.count
}

func (m *PermutationTime) EligibleTimeMaxMethod(timeArr []int) []int {
	m.EligibleTimeNumMethod(timeArr)
	return m.maxTime
}

func (m *PermutationTime) roll(depth int) {
	if depth == len(m.timeArr) && m.verify(m.timeArr) {
		m.upDateAns()
		return
	}
	for i := depth; i < len(m.timeArr); i++ {
		m.timeArr[i], m.timeArr[depth] = m.timeArr[depth], m.timeArr[i]
		m.roll(depth + 1)
		m.timeArr[i], m.timeArr[depth] = m.timeArr[depth], m.timeArr[i]
	}
}

func (m *PermutationTime) upDateAns() {
	for i := 0; i < len(m.timeArr); i++ {
		if m.timeArr[i] > m.maxTime[i] {
			m.maxTime = make([]int, len(m.timeArr))
			copy(m.maxTime, m.timeArr)
			m.count++
			return
		}
	}
}

func (m *PermutationTime) verify(array []int) bool {
	if len(array) != 4 {
		return false
	}
	if array[0] > 2 || (array[0] == 2 && array[1] >= 4) {
		return false
	}
	if array[2] >= 6 {
		return false
	}
	return true
}
